package com.zoe.vhr.utils;

import cn.hutool.core.map.MapUtil;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Author Zoe.Zhang
 * @Date: 2021/08/11
 * @Description 文件上传
 */
public class MultipartFileUtil {

    private static Boolean preCheckMultipart(HttpServletRequest httpServletRequest) {
        if (httpServletRequest instanceof MultipartRequest) {
            return true;
        }
        return false;
    }

    /**
     * 获取单个文件,一个key只会返回一个文件,即使这个key->包含多个文件
     *
     * @return
     */
    public static MultipartFile getSingleFile(HttpServletRequest request) {
        if (preCheckMultipart(request)) {
            Map<String, MultipartFile> fileMap = ((MultipartRequest) request).getFileMap();
            if (MapUtil.isEmpty(fileMap)) {
                return null;
            }
            Set<Map.Entry<String, MultipartFile>> multiFileSet = fileMap.entrySet();
            for (Map.Entry<String, MultipartFile> multipartFileEntry : multiFileSet) {
                return multipartFileEntry.getValue();
            }
        }
        return null;
    }

    /**
     * 返回多个文件;文件上传的name必须保持一致;一个key对应多个文件
     * 比如：
     * file: 123.jpg,
     * file: 534.jpg
     *
     * @return
     */
    public static List<MultipartFile> getMultipartFiles(HttpServletRequest request) {
        if (preCheckMultipart(request)) {
            MultipartRequest multipartRequest = (MultipartRequest) request;
            MultiValueMap<String, MultipartFile> multiFileMap = multipartRequest.getMultiFileMap();
            if (MapUtil.isEmpty(multiFileMap)) {
                return null;
            }
            Set<Map.Entry<String, List<MultipartFile>>> multiFileSet = multiFileMap.entrySet();
            for (Map.Entry<String, List<MultipartFile>> listEntry : multiFileSet) {
                return listEntry.getValue();
            }
        }
        return null;
    }

}
